package com.sx.zongzhi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.SpinnerPubAdapter;
import com.sx.zongzhi.bean.GlobalBean;
import com.sx.zongzhi.bean.KeyAreaDetailBean;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.PhotoBean;
import com.sx.zongzhi.bean.PublicBean;
import com.sx.zongzhi.net.ServiceFactory;
import com.sx.zongzhi.presenter.KeyAreaAddPest;
import com.sx.zongzhi.presenter.PublicListPest;
import com.sx.zongzhi.presenter.UploadFilePest;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.IKeyAreaAddView;
import com.sx.zongzhi.view.IPublicBeanView;
import com.sx.zongzhi.view.UploadFileView;
import com.sx.zongzhi.widget.LoadDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.sx.zongzhi.R.string.submit;


/**
 * 重点区域编辑
 */
public class KeyAreaEditActivity extends BaseActivity implements IPublicBeanView ,
        IKeyAreaAddView,UploadFileView{

    @BindView(R.id.imv_Head) ImageView imv_Head;
    @BindView(R.id.et_KeyAreaName) EditText et_KeyAreaName;
    @BindView(R.id.sp_KeyAreaType) Spinner sp_KeyAreaType;
    @BindView(R.id.et_AreaAddress) EditText et_AreaAddress;
    @BindView(R.id.et_Police) EditText et_Police;
    @BindView(R.id.et_Header) EditText et_Header;
    @BindView(R.id.et_Telephone) EditText et_Telephone;
    @BindView(R.id.et_Phone) EditText et_Phone;
    @BindView(R.id.sp_Attention) Spinner sp_Attention;
    @BindView(R.id.rg_Danger) RadioGroup rg_Danger;
    @BindView(R.id.rbt_Yes) RadioButton rbt_Yes;
    @BindView(R.id.rbt_No) RadioButton rbt_No;
    @BindView(R.id.et_DangerState) EditText et_DangerState;
    @BindView(R.id.ll_DangerState) LinearLayout ll_DangerState;
    @BindView(R.id.et_DangerChange) EditText et_DangerChange;
    @BindView(R.id.ll_DangerChange) LinearLayout ll_DangerChange;
    @BindView(R.id.et_Remark) EditText et_Remark;

    private List<GlobalBean> areaType=new ArrayList<>();
    private List<GlobalBean> AttentionList=new ArrayList<>();
    //区域id
    private String keyAreaId="";
    private String orgId="";
    //详情
    private KeyAreaDetailBean detailBean;
    private KeyAreaAddPest areaAddPest;
    /**更换的图片*/
    private String path="";

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_key_area_edit);
        ButterKnife.bind(this);
        setTitleRight(submit);
        keyAreaId=getIntent().getStringExtra("keyAreaId");
        detailBean= (KeyAreaDetailBean) getIntent().getSerializableExtra("KeyAreaDetailBean");
        orgId= getIntent().getStringExtra("orgId");
        initView();
        initData();
    }

    private void initData() {
        areaAddPest=new KeyAreaAddPest(this);
        PublicListPest publicListPest=new PublicListPest(this);
        publicListPest.getPublicList("区域类别");
        publicListPest.getPublicList("社会关注程度");
        rg_Danger.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId==R.id.rbt_Yes){
                    ll_DangerChange.setVisibility(View.VISIBLE);
                    ll_DangerState.setVisibility(View.VISIBLE);
                }else if (checkedId==R.id.rbt_No){
                    ll_DangerChange.setVisibility(View.GONE);
                    ll_DangerState.setVisibility(View.GONE);
                }
            }

        });
    }

    private void initView() {
        if (detailBean!=null){//修改
            setTitleName(R.string.key_area_edit);
            et_KeyAreaName.setText(detailBean.getName());
            et_AreaAddress.setText(detailBean.getAddress());
            et_Police.setText(detailBean.getNativePolice());
            et_Header.setText(detailBean.getLeader());
            et_Telephone.setText(detailBean.getTelephone());
            et_Phone.setText(detailBean.getMobile());

            if (detailBean.isHasDanger()){
                rbt_Yes.setChecked(true);
                et_DangerChange.setText(detailBean.getTreatDanger());
                et_DangerState.setText(detailBean.getDangerDes());
            }else {
                rbt_No.setChecked(true);
                ll_DangerChange.setVisibility(View.GONE);
                ll_DangerState.setVisibility(View.GONE);
            }
            et_Remark.setText(detailBean.getRemark());
            String path= ServiceFactory.NEW_API_BASE_URL+ File.separator+detailBean.getImgUrl();
            RequestOptions options = new RequestOptions()
                    .centerCrop()
                    .placeholder(R.mipmap.img_enterprise)
                    .error(R.mipmap.img_enterprise)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
            Glide.with(this)
                    .load(path)
                    .apply(options)
                    .into(imv_Head);
        }else {
            setTitleName(R.string.key_area_add);
        }
    }



    @OnClick({R.id.tv_right,R.id.rl_Head})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.tv_right://提交
                submit();
                break;
            case R.id.rl_Head://更换头像
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(true)// 是否可预览图片
                        .enableCrop(true)
                        .compress(true)
                        .compressGrade(Luban.CUSTOM_GEAR)
                        .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
        }
    }

    private void submit() {
        String keyAreaName=et_KeyAreaName.getText().toString().trim();
        if (keyAreaName.length()<1||keyAreaName.length()>20){
            et_KeyAreaName.setError("1~20个字");
            return;
        }
        if(areaType.size()<1){
            ToastUtils.showToast(this,"请选择重点区域类别");
            return;
        }
        String police=et_Police.getText().toString().trim();
        if (police.length()<1||police.length()>25){
            et_Police.setError("1~25个字");
            return;
        }
        String phone=et_Phone.getText().toString().trim();
        if (!BaseUtil.isEmpty(phone)&&!BaseUtil.isMobile(phone)){
            et_Phone.setError("请输入正确的手机号");
            return;
        }
        LoadDialog.show(this,"检测同名");
        //判断有没有相同的名称
        areaAddPest.keyAreaName("hasImportantArea.action",orgId,keyAreaName,
                    BaseUtil.isEmpty(keyAreaId)?"":keyAreaId);

    }

    private void submitDone() {
        if (detailBean==null){
            detailBean=new KeyAreaDetailBean();
        }
        detailBean.setName(et_KeyAreaName.getText().toString().trim());
        String areaType=((GlobalBean)sp_KeyAreaType.getSelectedItem()).getId();
        GlobalBean typeBean = new GlobalBean();
        typeBean.setId(areaType);
        detailBean.setType(typeBean);
        detailBean.setAddress(et_AreaAddress.getText().toString().trim());
        detailBean.setNativePolice(et_Police.getText().toString().trim());
        detailBean.setLeader(et_Header.getText().toString().trim());
        detailBean.setTelephone(et_Telephone.getText().toString().trim());
        detailBean.setMobile(et_Phone.getText().toString().trim());
        detailBean.setHasDanger(rbt_Yes.isChecked());
        detailBean.setDangerDes(et_DangerState.getText().toString().trim());
        detailBean.setTreatDanger(et_DangerChange.getText().toString().trim());
        detailBean.setRemark(et_Remark.getText().toString().trim());
        GlobalBean atten = (GlobalBean) sp_Attention.getSelectedItem();
        if (atten!=null){
            String attention=atten.getId();
            GlobalBean aBean=new GlobalBean();
            aBean.setId(attention);
            detailBean.setAttentionExtent(aBean);
        }
        LoadDialog.show(this,"正在提交");
        if (BaseUtil.isEmpty(keyAreaId)){//新增
            areaAddPest.AddKeyArea("addImportantArea.action","",orgId,detailBean,path);
        }else {//编辑
            areaAddPest.AddKeyArea("updateImportantArea.action",keyAreaId,orgId,detailBean,path);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                path = picUrls.get(0).getCompressPath();
                Glide.with(this)
                        .load(path)
                        .into(imv_Head);
            }
        }
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(this);
        ToastUtils.showToast(this,message);
    }



    @Override
    public void getPublicList(PublicBean publicBean) {
        if ("区域类别".equals(publicBean.getDomainName())){
            areaType=publicBean.getDicts();
            if (areaType!=null){
                SpinnerPubAdapter adapter=new SpinnerPubAdapter(this,R.layout.item_text,areaType);
                sp_KeyAreaType.setAdapter(adapter);
                if (detailBean!=null){
                    showAreaType();
                }
            }
        }
        if ("社会关注程度".equals(publicBean.getDomainName())){
            AttentionList=publicBean.getDicts();
            if (AttentionList!=null){
                SpinnerPubAdapter adapter=new SpinnerPubAdapter(this,R.layout.item_text,AttentionList);
                sp_Attention.setAdapter(adapter);
                if (detailBean!=null){
                    showAttention();
                }
            }
        }
    }

    private void showAttention() {
        for (int i=0;i<AttentionList.size();i++){
            if (AttentionList.get(i).getId().equals( detailBean.getAttentionExtent().getId())){
                sp_Attention.setSelection(i);
            }
        }
    }

    private void showAreaType() {
        for (int i=0;i<areaType.size();i++){
            if (areaType.get(i).getId().equals( detailBean.getType().getId())){
                sp_KeyAreaType.setSelection(i);
            }
        }
    }

    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
       if (beans!=null&&beans.size()>0){
           path=beans.get(0).getPath();
       }
        submitDone();
    }

    @Override
    public void addSuccess(Boolean result) {
        LoadDialog.dismiss(this);
        if (result) {
            ToastUtils.showToast(this, "提交成功");
            MyRxBus.get().post(new MsgEvent<>("KeyAreaActivity", 1, "提交成功"));
            finish();
        }else {
            ToastUtils.showToast(this, "提交失败");
        }
    }

    @Override
    public void nameSuccess(Boolean result) {
        if (!result){
            if(BaseUtil.isEmpty(path)){
                submitDone();
            }else {
                LoadDialog.show(this,"正在上传图片...");
                UploadFilePest filePest=new UploadFilePest(this);
                List<File> files=new ArrayList<>();
                files.add(new File(path));
                filePest.uploadFile(this,files);
            }
        }else {
            LoadDialog.dismiss(this);
            ToastUtils.showToast(this,"名称已存在，请更改名称");
        }
    }
}
